package com.yuyang.wifi.activitys.web;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.R;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.utils.DCommManager;
import com.yuyang.wifi.utils.FileUtil;
import com.yuyang.wifi.utils.HttpUtil;
import com.yuyang.wifi.utils.LogUtils;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.PathUtils;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.views.NormalWhiteTopBar;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;

import java.io.File;

import androidx.annotation.NonNull;
import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class WebViewActivity extends BaseActivity {

    private String mDictionary, mLocalPath;
    private RequestHandle mDownloader;


    @BindView(R.id.tool_bar)
    NormalWhiteTopBar toolBar;
    @BindView(R.id.web_view)
    WebView mWebView;
    private TextView mTitle;
    private String url;
    private String mFileUrl;


    @Override
    protected void initActionBar() {
        mTitle = toolBar.setActionBarCentreTitle("");
        toolBar.setsetActionBarLeftIcon(R.mipmap.toolbar_left_arrow_back_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void initContentView() {

        String title = getIntent().getExtras().getString("title");
        url = getIntent().getExtras().getString("url");

        //mWebView.loadUrl("file:///android_asset/normal.html");

        if (!TextUtils.isEmpty(title)) {
            mTitle.setText(title);
        }
        initWebView();

    }

    private void initWebView() {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JavaScriptInterface(this), "android");
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setDownloadListener(new FileDownLoadListener());
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // dismissDialog();
            }


            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // dismissDialog();
                mWebView.setVisibility(View.GONE);
                //ToastUtils.showShortToast(getApplicationContext(), "请求失败，请退出重试");

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
                // WebView可以加载Http、Https和file这三种URL，所以除了这三种URL外，其他都要另外处理
                if (!url.startsWith("http") && !url.startsWith("file") && !url.startsWith("https")) {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (Exception e) {
                        // 如果找不到合适的APP来加载URL，则会抛出异常
                        e.printStackTrace();
                    }
                    return true;
                }
                view.loadUrl(url);
                return true;
               // return super.shouldOverrideUrlLoading(view, url);
            }
        });
        mWebView.setWebChromeClient(new HarlanWebChromeClient(this));
        // synCookies(this, url);
        mWebView.loadUrl(url);
    }


    /**
     * 当下载文件时打开系统自带的浏览器进行下载，当然也可以对捕获到的 url 进行处理在应用内下载。
     **/
    private class FileDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
           // mFileUrl = url;
//            if (TextUtils.isEmpty(mLocalPath)) {
//                requestSDPermission();
//            } else {
//                installApk(mLocalPath);
//            }
           // requestSDPermission();

        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void down() {
        final String fileUrl = mFileUrl;
        mDictionary = PathUtils.getApkPath(this);
        mDownloader = HttpUtil.downH5(fileUrl, new FileAsyncHttpResponseHandler(this) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                LogUtils.e("onSuccess", file.getPath());
                String movieFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                String localPath = mDictionary + movieFileName;
                LogUtils.e("localPath", localPath);
                try {
                    FileUtil.copyFile(new File(file.getPath()), new File(localPath));
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mLocalPath = localPath;
                installApk(mLocalPath);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                LogUtils.e("onFailure", statusCode + "");
                ToastUtils.showShortToast(WebViewActivity.this, "下载失败，请稍后再试");

                mLocalPath = "";

            }

            @Override
            public void onProgress(final long bytesWritten, final long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                int progress = (int) (bytesWritten * 100 / totalSize);
                // updateProgress(progress);
            }
        });
    }

    public void installApk(String path) {
        MyApplication.logEvent(WebViewActivity.this, "用户强制升级");
        File apkfile = new File(path);
        if (!apkfile.exists() && apkfile.length() > 10) {
            return;
        }

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        Uri uri = DCommManager.makeUri(MyApplication.getInstance(), apkfile);
        i.setDataAndType(uri, "application/vnd.android.package-archive");
        LogUtils.e("path", path);
        LogUtils.e("prividerpath", uri.getPath());
        startActivity(i);
    }

    @Override
    protected void onDestroy() {
        if (mDownloader != null) {
            mDownloader.cancel(true);
        }
        super.onDestroy();
    }


}
